package view;

import com.alibaba.fastjson.JSON;
import constant.ConstDataBase;
import model.ViewForExpress;
import model.ViewForGrid;
import model.ViewForReport;
import pond.common.Convert;
import pond.common.FILE;
import pond.common.S;
import pond.common.STRING;
import pond.db.DB;
import pond.db.Record;
import pond.db.sql.Criterion;
import pond.db.sql.Sql;
import pond.db.sql.SqlSelect;
import pond.web.Render;
import pond.web.Router;
import service.DataBaseService;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by sky_wang on 2017/7/19.
 */
public class Table extends Router {
    private DataBaseService dataBaseService;
    public Table (DataBaseService dataBaseService){
        this.dataBaseService = dataBaseService;
    }
    {
        get("/list", (req, resp) -> {
            resp.render(Render.json(dataBaseService.getDataTableList()));
        });

        get("/:name/coloumn/:coloumn_name/distinct", (req, resp) -> {
            String coloumn_name = req.param("coloumn_name");
            String table_name = req.param("name");
            String sql = "select distinct " + coloumn_name + " from " + table_name + ";";
            List<Record> ret = dataBaseService.getDB().get(t -> t.query(sql));
            resp.render(Render.json(ret));
        });

        get("/:main_table/:sub_table/isRelated", (req, resp) -> {
            String mainTableName = req.param("main_table");
            String subTableName = req.param("sub_table");
            if (STRING.isBlank(mainTableName) || STRING.isBlank(subTableName)) {
                resp.send("null parm");
            }

            if (dataBaseService.isHasRelation(mainTableName, subTableName)) {
                resp.send("ok");
            } else {
                resp.send(mainTableName + " and " + subTableName + " no relation!");
            }
        });


    }
}
